import React, { useCallback, useEffect, useImperativeHandle, useMemo, useState } from 'react'
import styled from 'styled-components'
import Item, { Props as ItemProps } from './Item';
import { useTranslation } from 'react-i18next';
import Icon from '../../component/Icon';
import { useSearchParams } from 'react-router-dom';
import WebApp from '@twa-dev/sdk';
import { WithDrawInfo, withdrawInfo } from '../../service';
import Loading from '../../component/Loading';

interface Props {
    className?: string
}

type FormItemType = ItemProps & { id: string, formType?: 'input' | 'tips' }

const Container = styled.div`
    flex: 1;
    >:not(:first-child) {
        margin-top: 1.3125rem;
    }
`

const All = styled.div`
    padding: 0 .875rem;
    box-sizing: border-box;
    color: #98FBD3;
`

const Scan = styled(Icon)`
    margin: 0 .875rem;
`
const Tips = styled.span`
    margin: 1.0625rem 0 1.375rem 0;
    font-size: .875rem;
    color: rgba(255, 255, 255, 0.7);
    display: flex;
    justify-content: space-between;
`

const FormIds = {
    Asset: 'asset',
    Network: 'network',
    Comment: 'comment',
    Address: 'address',
    Count: 'count',
    Fee: 'fee',
    Available: 'available',
}

export interface ContentRef {
    values: () => { [key: string]: string }
}

const Content: React.FC<Props & React.RefAttributes<ContentRef>> = React.forwardRef<ContentRef, Props>(({ className }, ref) => {
    const { t } = useTranslation()
    const [params] = useSearchParams()
    const [list, setList] = useState<Array<FormItemType>>([])
    const [data, setData] = useState<{ [key: string]: string }>()
    const [info, setInfo] = useState<WithDrawInfo>()
    const [loading, setLoading] = useState(false)
    const ton = useMemo(() => info?.available || params.get('ton') || '', [params, info?.available])
    useImperativeHandle(ref, () => ({
        values: () => data || {}
    }))

    const onSuffixClick = useCallback((event: React.MouseEvent<HTMLElement, MouseEvent>, id: string) => {
        if (id === FormIds.Count) {
            setData(pre => ({
                ...pre,
                [id]: ton
            }))
            return
        }

        if (id === FormIds.Address) {
            event.stopPropagation()
            WebApp.showScanQrPopup({ text: 'Earth' }, (text: string) => {
                setData(pre => ({
                    ...pre,
                    [id]: text
                }))
                WebApp.closeScanQrPopup()
            })
        }
    }, [ton])

    const fetchData = useCallback(async () => {
        setLoading(true)
        const res = await withdrawInfo();
        setLoading(false)
        if (!res.success) {
            return
        }

        const array: Array<FormItemType> = [
            // { id: FormIds.Asset, title: t('withdraw.form.asset.title'), default: res.data?.currency || t('withdraw.form.asset.default'), disable: true, backgroundColor: 'transparent' },
            { id: FormIds.Network, title: t('withdraw.form.network.title'), default: res.data?.chain || t('withdraw.form.network.default'), disable: true },
            { id: FormIds.Comment, title: t('withdraw.form.comment.title'), placeholder: t('withdraw.form.comment.placeholder'), tips: t('withdraw.form.comment.tips') },
            {
                id: FormIds.Address, title: t('withdraw.form.address.title'), placeholder: t('withdraw.form.address.placeholder'), suffix: <Scan
                    width='1.5625rem'
                    name='icon_scan'
                    onClick={(event) => onSuffixClick(event, FormIds.Address)}
                />
            },
            { id: FormIds.Count, title: t('withdraw.form.count.title'), placeholder: t('withdraw.form.count.placeholder_num', { num: res.data?.min || '0.05' }), unit: res.data?.currency || t('withdraw.form.count.unit'), type: 'number', suffix: <All onClick={(event) => onSuffixClick(event, FormIds.Count)}>{t('withdraw.form.count.suffix')}</All> },
            { id: FormIds.Fee, title: t('withdraw.form.fee.title'), default: String(res.data?.fee || 0), unit: res.data?.currency || t('withdraw.form.fee.unit'), formType: 'tips' },
            { id: FormIds.Available, title: t('withdraw.form.balance.title'), default: String(res.data?.available || params.get('ton') || 0), unit: res.data?.currency || t('withdraw.form.balance.unit'), formType: 'tips' },
        ]

        setInfo(res.data)
        setList(array)
        setData(array.reduce((draft, value) => {
            draft[value.id] = value.default
            return draft
        }, {} as any))

    }, [t, params, onSuffixClick])


    useEffect(() => {
        fetchData()
    }, [fetchData])

    const onChange = (value: string, item: FormItemType) => {
        if (item.id === FormIds.Count && (Number(value || '') > Number(ton))) {
            value = ton
        }
        setData(pre => ({
            ...pre,
            [item.id]: value
        }))
    }

    return <Container className={className}>
        {list.map((item) => item.formType === 'tips' ?
            <Tips key={item.id}>
                <span>{item.title}</span>
                <span>{`${item.default}${item.unit}`}</span>
            </Tips> :
            <Item
                key={item.id}
                {...item}
                value={data?.[item.id]}
                onValueChange={(value) => onChange(value, item)}
            />)}
        <Loading show={loading} />
    </Container>
})
export default Content